﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

/// <summary>
/// Summary description for ShoppingCart
/// </summary>
public class ShoppingCart:DataTable
{
	//Khoi tao gio hang
    public ShoppingCart()
	{
        this.Columns.Add("MaXe", typeof(string)).DefaultValue = "";
        this.Columns.Add("TenXe", typeof(string)).DefaultValue = "";
        this.Columns.Add("GiaBan", typeof(double)).DefaultValue = 0;
        this.Columns.Add("SoLuongMua", typeof(int)).DefaultValue = 0;
        this.Columns.Add("ThanhTien", typeof(double), "GiaBan*SoLuongMua");

        this.PrimaryKey = new DataColumn[] { this.Columns["MaXe"] };
	}

    //Them san pham vao gio hang
    public void Add(string maxe, int soluong)
    {
        this.AddProduct(maxe, soluong, false);
    }
    
    //Cap nhat lai gio hang
    public void Update(string maxe, int soluong)
    {
        this.AddProduct(maxe, soluong, true);
    }

    //Xoa san pham khoi gio hang
    public void Remove(string maxe)
    {
        try
        {
            DataRow Product = this.Rows.Find(maxe);
            this.Rows.Remove(Product);
        }
        catch
        {
            Console.WriteLine("Product not found !");
        }
    }

    //Tong so tien mua hang
    public double Total
    {
        get
        {
            object value = this.Compute("SUM(ThanhTien)", "");
            return value == DBNull.Value ? 0 : (double)value;
        }
    }

    //so luong san pham co trong gio
    public int Count
    {
        get
        {
            object value = this.Compute("SUM(SoLuongMua)", "");
            return value == DBNull.Value ? 0 : Convert.ToInt32(value);            
        }
    }

    //Them xe vao gio
    private void AddProduct(string maxe, int soluong, bool Update)
    {
        try
        {
            DataRow Item = this.Rows.Find(maxe);
            Item["SoLuongMua"] = soluong + (Update ? 0 : (int)Item["SoLuongMua"]);
        }
        catch
        {
            String sql = "SELECT tt.MaXe, tt.TenXe, g.GiaBan, " + soluong + " as SoLuongMua FROM ThongTinCoBan tt,gia g WHERE tt.MaXe=g.MaXe AND tt.MaXe=@maxe";
            DataBase.Fill(this, sql, "@maxe", maxe);
        }
    }
}
